<template>
  <div class="content">
    <!-- 创建规则 -->
    <div class="dialog">
      <el-form :model="createrule" label-width="120px">
        <el-form-item label="标签规则名称" required="true">
          <el-input v-model="createrule.title" maxlength="15" show-word-limit type="text" placeholder="请输入标签规则名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="createrule.desc" maxlength="50" show-word-limit type="textarea" placeholder="请输入描述" resize="none" />
        </el-form-item>
        <el-form-item label="有效期">
          <div>
            <el-radio v-model="createrule.validity_type" :label="1">永久</el-radio>
            <el-radio v-model="createrule.validity_type" :label="2">自定义时间段</el-radio>
            <el-date-picker v-model="timebyself" value-format="YYYY-MM-DD HH:mm:ss" v-if="createrule.validity_type == 2" type="datetimerange" :append-to-body="false" start-placeholder="开始时间" end-placeholder="结束时间" :disabledDate="disabledDate" />
          </div>
        </el-form-item>
        <el-form-item label="生效员工" required="true">
          <div>
            <el-button @click="choosemember" class="common">选择员工</el-button>
            <span style="margin: 0 10px 10px 0" v-for="(item, index) in employee" :key="index"
              ><el-tag closable :key="item" @close="handleclose(item)">{{ item.name }}</el-tag></span
            >
          </div>
        </el-form-item>
        <el-form-item label="关键词设置" required="true">
          <div>
            <span class="tips">聊天中包含以下关键词则自动打上标签。同时添加多个关键词，请用“空格隔开”，回车添加。</span>
            <el-row>
              <el-col :span="4">
                <el-checkbox v-model="isaccurate" label="精准匹配：" />
              </el-col>
              <el-col :span="20"
                ><span style="margin: 0 10px 10px 0" v-for="(item, index) in createrule.accurate_match" :key="index">
                  <el-tag closable @close="delaccuate(index)">{{ item }}</el-tag>
                </span></el-col
              >
            </el-row>
            <el-row>
              <el-col :span="14"><el-input v-model="accurate_text" @keyup.enter="keyup(0)" :disabled="!isaccurate"></el-input></el-col>
            </el-row>
            <el-row>
              <el-col :span="4"><el-checkbox v-model="isfuzzy" label="模糊匹配：" /></el-col>
              <el-col :span="20"
                ><span style="margin: 0 10px 10px 0" v-for="(item, index) in createrule.fuzzy_match" :key="index">
                  <el-tag closable @close="delfuzzy(index)">{{ item }}</el-tag>
                </span></el-col
              >
            </el-row>
            <el-row>
              <el-col :span="14"><el-input v-model="fuzzy_text" @keyup.enter="keyup(1)" :disabled="!isfuzzy"></el-input></el-col>
            </el-row>
          </div>
        </el-form-item>
        <el-form-item label="自动打标" required="true">
          <div>
            <el-button @click="opentag" class="common">选择标签</el-button>
            <span style="margin: 0 10px 10px 0" v-for="(item, index) in taglist" :key="index"
              ><el-tag closable :key="item" @close="closetag(item)">{{ item.name }}</el-tag></span
            >
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="btn">
      <el-button @click="router.go(-1)">取消</el-button>
      <el-button type="primary" @click="go">保存</el-button>
    </div>
    <ZWDepart ref="DepartRef" @submit="getDepart" :type="1"></ZWDepart>
    <BatchLabel ref="BatchLabelRef" @save="getTagsFun" />
  </div>
</template>
<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import router from '@/router'
  import { ElMessage } from 'element-plus'
  import ZWDepart from '@/components/ZWDepart.vue'
  import BatchLabel from '@/components/BatchLabel.vue'
  import { getDetail, edit } from '@/api/customer/tag/chatontag'
  import { time } from 'echarts'
  const timebyself = ref([]) //创建规则的自定义时间段
  const accurate_text = ref('') //创建规则的精准匹配
  const fuzzy_text = ref('') //创建规则模糊匹配
  const isaccurate = ref(false)
  const isfuzzy = ref(false)
  const DepartRef = ref(null)
  const taglist = ref([])
  const BatchLabelRef = ref(null)
  const employee = ref([])
  let createrule = reactive({
    title: '',
    desc: '',
    validity_type: '', //1 长久有效 2 自定义时间段
    start_time: '', //2022-03-15 16:28:28  validity_type = 2 必填
    end_time: '', //2022-03-15 16:28:28 validity_type = 2 必填
    effective_employee: [], //选中的员工
    accurate_match: [], //精准匹配
    fuzzy_match: [], //模糊匹配  模糊匹配 与  精准匹配 不能同时为空
    select_label: []
  })
  // 获取编辑详情
  const getlist = () => {
    getDetail({ cust_chat_tag_id: router.currentRoute.value.query.id }).then((res: any) => {
      for (let key in createrule) {
        createrule[key] = res[key]
      }
      if (res.validity_type == 2) {
        timebyself.value = [res.start_time, res.end_time]
      }
      taglist.value = res.select_label
      employee.value = res.effective_employee
      if (res.accurate_match.length > 0) {
        isaccurate.value = true
      }
      if (res.fuzzy_match.length > 0) {
        isfuzzy.value = true
      }
    })
  }
  getlist()
  // 回车添加标签r
  const keyup = (data: any) => {
    let reg = /\s+/
    if (data == 0 && accurate_text.value) {
      let data = accurate_text.value.trim().split(reg)
      let maxData = data.filter((item) => item.length > 15) //获取字数超过15的
      let minData = data.filter((item) => item.length < 16) //获取字数限制在15以内的
      createrule.accurate_match = createrule.accurate_match.concat(minData)
      createrule.accurate_match = Array.from(new Set(createrule.accurate_match)) //去重
      if (maxData.length > 0) {
        accurate_text.value = maxData.join(' ')
        ElMessage.warning('关键词长度不能超过15个字')
      } else {
        accurate_text.value = ''
      }
    } else if (data == 1 && fuzzy_text.value) {
      let data = fuzzy_text.value.trim().split(reg)
      let maxData = data.filter((item) => item.length > 15) //获取字数超过15的
      let minData = data.filter((item) => item.length < 16) //获取字数限制在15以内的
      createrule.fuzzy_match = createrule.fuzzy_match.concat(minData)
      createrule.fuzzy_match = Array.from(new Set(createrule.fuzzy_match)) //去重
      if (maxData.length > 0) {
        accurate_text.value = maxData.join(' ')
        ElMessage.warning('关键词长度不能超过15个字')
      } else {
        accurate_text.value = ''
      }
    }
  }
  const go = () => {
    if (!createrule.title) {
      ElMessage({ message: '请输入标签规则名称', type: 'warning' })
      return
    }
    if (employee.value.length == 0) {
      ElMessage({ message: '请选择员工', type: 'warning' })
      return
    }
    if (!((isaccurate.value && createrule.accurate_match.length > 0) || (isfuzzy.value && createrule.fuzzy_match.length > 0))) {
      ElMessage({ message: '关键词设置不能为空', type: 'warning' })
      return
    }
    if (taglist.value.length == 0) {
      ElMessage({ message: '请选择标签', type: 'warning' })
      return
    }
    createrule.effective_employee = []
    createrule.select_label = []
    taglist.value.forEach((item: any) => {
      createrule.select_label.push({ id: item.id, name: item.name })
    })
    employee.value.forEach((item: any) => {
      createrule.effective_employee.push({ id: item.id, name: item.name })
    })
    if (createrule.validity_type == 1) {
      createrule.end_time = ''
      createrule.start_time = ''
    } else {
      createrule.end_time = timebyself.value[1]
      createrule.start_time = timebyself.value[0]
    }
    var param = {
      ...createrule,
      cust_chat_tag_id: router.currentRoute.value.query.id
    }
    edit(param).then((res: any) => {
      ElMessage({ message: '编辑成功', type: 'success' })
      router.go(-1)
    })
  }
  const choosemember = () => {
    DepartRef.value.limit = 1
    DepartRef.value.isExternal = true
    DepartRef.value.selectedMember = [...employee.value]
    DepartRef.value.departVisble = true
  }
  const getDepart = (res: any) => {
    employee.value = res
    DepartRef.value.departVisble = false
  }
  const handleclose = (res: any) => {
    employee.value.splice(employee.value.indexOf(res), 1)
  }
  const opentag = () => {
    BatchLabelRef.value.hasConditiion = false
    BatchLabelRef.value.dialogData.labelChooseType = 2
    BatchLabelRef.value.chooseDataArr = []
    if (taglist.value.length > 0) {
      BatchLabelRef.value.chooseDataArr = [...taglist.value]
    }
    BatchLabelRef.value.dialogVisible = true
  }
  const getTagsFun = (data: any) => {
    taglist.value = [...data.data]
  }
  const delaccuate = (res: any) => {
    createrule.accurate_match.splice(res, 1)
  }
  const delfuzzy = (res: any) => {
    createrule.fuzzy_match.splice(res, 1)
  }
  const closetag = (res: any) => {
    taglist.value.splice(taglist.value.indexOf(res), 1)
  }
  //禁用之前的时间
  const disabledDate = (time: any) => {
    return time.getTime() < Date.now() - 8.64e7
  }
</script>
<style scoped lang="scss">
  .content {
    padding: 20px;
    background: #ffffff;
    .common {
      margin-right: 10px;
    }
    .dialog {
      textarea {
        resize: none !important;
      }
      .tips {
        font-size: 14px;
        font-weight: 300;
        color: #585858;
        line-height: 20px;
      }
    }
    .btn {
      display: flex;
      justify-content: center;
      padding: 11px 0 0 0;
      border-top: 1px solid #d9d9d9;
    }
  }
</style>
